<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Registro extends CI_Controller {
    function news(){
      $this->load->model("user");
      $this->load->library('form_validation');
      $this->form_validation->set_rules('email', 'email', 'trim|required|valid_email');  
             if ($this->form_validation->run() == FALSE)
                {     
                        
                      $this->load->view('home/header.php' );
                      $this->load->view('home/index.php' );
                      $this->load->view('home/footer.php');
              
                }else{
                    $contacto=array("email"=>$this->input->post('email'));
                    $this->user->guardarNewsS($contacto);
                      
                      $data["newsguardado"] = true;  
                      $this->load->view('home/header.php' );
                      $this->load->view('home/index.php',   $data);
                      $this->load->view('home/footer.php');
                    
                }
        
        
        
        
    }
    function __construct() {
        parent::__construct();
        /* cargo librerias necesarias */
        $this->load->helper('url');
        $this->load->database();
        $this->load->library('session');
    }
    function subir_img_instituto(){
         //Some Settings
    $ThumbSquareSize        = 250; //Thumbnail will be 200x200
    $BigImageMaxSize        = 250; //Image Maximum height or width
    $ThumbPrefix            = "thumb_"; //Normal thumb Prefix

    $DestinationDirectory           = '/home/expoeduc/public_html/beta/public/images/instituciones/'; //Upload Directory ends with / (slash)
    $Quality            = 100;
        
        //check if form was submitted though ajax
        $xhr = $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'; 
    if (!$xhr){
            die('Data wasn\'t sent though ajax!');
        }

       // check $_FILES['ImageFile'] array is not empty
    // "is_uploaded_file" Tells whether the file was uploaded via HTTP POST
    if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
    {
            die('Something went wrong with Upload!'); // output error when above checks fail.
    }

    // Random number for both file, will be added after image name
    $RandomNumber   = rand(0, 9999999999);

    // Elements (values) of $_FILES['ImageFile'] array
    //let's access these values by using their index position
    $ImageName      = str_replace(' ','-',strtolower($_FILES['ImageFile']['name']));
    $ImageSize      = $_FILES['ImageFile']['size']; // Obtain original image size
    $TempSrc        = $_FILES['ImageFile']['tmp_name']; // Tmp name of image file stored in PHP tmp folder
    $ImageType      = $_FILES['ImageFile']['type']; //Obtain file type, returns "image/png", image/jpeg, text/plain etc.

    //Let's use $ImageType variable to check wheather uploaded file is supported.
    //We use PHP SWITCH statement to check valid image format, PHP SWITCH is similar to IF/ELSE statements
    //suitable if we want to compare the a variable with many different values
    switch(strtolower($ImageType))
    {
        case 'image/png':
            $CreatedImage =  imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
            break;
        case 'image/gif':
            $CreatedImage =  imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
            break;
        case 'image/jpeg':
        case 'image/pjpeg':
            $CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
            break;
        default:
            die('Unsupported File!'); //output error and exit
    }

    //PHP getimagesize() function returns height-width from image file stored in PHP tmp folder.
    //Let's get first two values from image, width and height. list assign values to $CurWidth,$CurHeight
    list($CurWidth,$CurHeight)=getimagesize($TempSrc);
    //Get file extension from Image name, this will be re-added after random name
    $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
    $ImageExt = str_replace('.','',$ImageExt);

    //remove extension from filename
    $ImageName      = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);

    //Construct a new image name (with random number added) for our new image.
    $NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
    //set the Destination Image
    $thumb_DestRandImageName    = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name
    $DestRandImageName          = $DestinationDirectory.$NewImageName; //Name for Big Image

    //Resize image to our Specified Size by calling resizeImage function.
    if($this->resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
    {
        //Create a square Thumbnail right after, this time we are using cropImage() function
        if(!$this->cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType))
            {
                echo 'Error Creating thumbnail';
            }
        /*
        At this point we have succesfully resized and created thumbnail image
        We can render image to user's browser or store information in the database
        For demo, we are going to output results on browser.
        */

        //Get New Image Size
        list($ResizedWidth,$ResizedHeight)=getimagesize($DestRandImageName);
        
     
      
        echo '<div><input name="imgsrc"  type="hidden" value="' . $DestinationDirectory .$NewImageName . '"/><img src="' .  site_url("/public/images/instituciones/") . '/'.$NewImageName.'" alt="Resized Image" height="'.$ResizedHeight.'" width="'.$ResizedWidth.'"></div>';
   
        

    }else{
        die('Resize Error'); //output error
    }

        
    }
    function tu_curso() {
        $this->load->model("city");
        $city = new city;
        
        
        $data["citys"] =  $city->getAllRecords();
        $this->load->view('home/header.php');
        $this->load->view('home/publica_tu_curso.php',$data);
        $this->load->view('home/footer.php');
    }
    function imagen() {
                $this->load->library('form_validation');
                $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		$this->form_validation->set_rules('titulo', 'Titulo', 'trim|required');
                $this->form_validation->set_rules('descripcion_corta', 'Descripcion corta', 'trim|required');
                $this->form_validation->set_rules('tipo_curso', 'Tipo curso', 'trim|required');
                $this->form_validation->set_rules('categoria', 'Categoria', 'trim|required');
                $this->form_validation->set_rules('palabras_claves', 'Palabras claves', 'trim|required');
                $this->form_validation->set_rules('descripcion', 'Descripcion', 'trim|required');
                $this->form_validation->set_rules('precio', 'Precio curso', 'trim|required|integer');
                $this->form_validation->set_rules('tipo_cobro', 'Tipo cobro', 'trim|required');
                $this->form_validation->set_rules('modalidad', 'Modalidad', 'trim|required');
                $this->form_validation->set_rules('tipo_duracion', 'Tipo duracion', 'trim|required');
                $this->form_validation->set_rules('valor_matricula', 'Valor de matricula', 'trim|required|integer');
                $this->form_validation->set_rules('meses_duracion', 'Meses de duración', 'trim|required|integer');
                $this->form_validation->set_rules('clases_semanales', 'Clases Semanales', 'trim|required|integer');
                
                 $data = $this->session->userdata('curso');
                if ($this->form_validation->run() == FALSE)
		{
                $this->load->view('home/header.php');
                $this->load->model("city");
                $city = new city;
                $data["citys"] =  $city->getAllRecords();
                $this->load->view('home/publica_tu_curso.php',$data);
                $this->load->view('home/footer.php');
                    
                    
                }else{
                        
                $this->load->view('home/header.php');
              
                    
                            $datacurso =array('curso'=> array(
                               'titulo'  => $this->input->post('titulo'),
                               'tipo_curso'     => $this->input->post('tipo_curso'),
                               'palabras_claves' => $this->input->post('palabras_claves'),
                               'categoria' => $this->input->post('categoria'),
                               'descripcion_corta' => $this->input->post('descripcion_corta'), 
                               'descripcion' => $this->input->post('descripcion'),
                               'objetivos' => $this->input->post('objetivos'),
                               'orientacion' => $this->input->post('orientacion'), 
                               'que_incluye' => $this->input->post('que_incluye'),
                               'requisitos' => $this->input->post('requisitos'),
                               'tipo_duracion' => $this->input->post('tipo_duracion'),
                               'meses_duracion' => $this->input->post('meses_duracion'),
                               'clases_semanales' => $this->input->post('clases_semanales'),
                               'precio' => $this->input->post('precio'), 
                               'es_gratuita' => $this->input->post('es_gratuita'),
                               'tipo_cobro' => $this->input->post('tipo_cobro'),
                               'valor_matricula' => $this->input->post('valor_matricula'),
                               'matricula' => $this->input->post('matricula'),
                               'modalidad' => $this->input->post('modalidad'),
                               'fecha_inicio_valor' => $this->input->post('fecha_inicio_valor'),
                               'foto_curso' => $this->input->post('foto_curso')
                           ));

             
                            $this->session->set_userdata($datacurso);
                            
                            
                            
                
                
                
                
            ;
                $data["palabras_claves"] = $this->input->post('palabras_claves');
                $data["titulo"] = $this->input->post('titulo');
                $data["descripcion_corta"] = $this->input->post('descripcion_corta');
                
                
                
                
                
                
                
                $this->load->view('home/seleccionar_imagen.php',$data);
                $this->load->view('home/footer.php');
                }
        
    }
    function subir_imagen() {
        
          
                $curso = $this->session->userdata('curso');
   
        
  
        $this->load->view('home/header.php');
        $this->load->view('home/subir_imagen.php',$curso);
        $this->load->view('home/footer.php');
    }
    function cargar_instituto() {
     //   print_r($_SERVER);
      
        //Foto del Curso
        if ($this->input->post('img_select')) {
            $img = $this->input->post('img_select');
            $this->session->set_userdata('foto_curso', $img);
        }
        //Si no esta logueado
        if (!$this->session->userdata('user_id')) {
            $data['mostrar_login'] = true;
            $this->load->view('home/header.php');
            $this->load->view('registro/registro.php', $data);
            $this->load->view('home/footer.php');
        } else {
            //Ya está logueado - Publica el curso
            $user_id = $this->session->userdata('user_id');
            $tiene_instituto = $this->verificar_usuario($user_id);
            if ($tiene_instituto == 0) {
                
        
                $this->load->model("city");
                $city = new city;
                $citys =  $city->getAllRecords();
                $data["citys"] = $citys;
                
                $this->load->view('home/header.php');
                $this->load->view('home/cargar_instituto.php',$data);
                $this->load->view('home/footer.php');
            } else {
                //Publica el curso con el instituto asociado
                $this->publicar_curso();
            }
        }
    }
    function verificar_usuario($user_id) {
        $sql = "SELECT instituto_id FROM usuarios_institutos WHERE user_id = $user_id";
        
        $num_row = $this->db->query($sql)->num_rows();
        if ($num_row != 0) {
            $res =  $this->db->query($sql)->result();
            return $res[0]->instituto_id; 
        }
        error_log('verificar:' . $num_row);
        return $num_row;
    }
    function publicar_curso() 
    {
        $this->load->helper('utilidades.php');
        $data = $this->session->all_userdata();
        $user_id = $this->session->userdata('user_id');
     
        $error = FALSE;
        //Verifica si viene del form de cargar institucion
       
        if ($this->verificar_usuario($user_id) === 0) {
     
            	$this->load->library('form_validation');
                $photoguarda = $this->input->post('imgsrc');
               
                $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		$this->form_validation->set_rules('nombre_institucion', 'Nombre institucion', 'trim|required');
                $this->form_validation->set_rules('tel1', 'Codigo pais', 'trim|required|numeric');
                $this->form_validation->set_rules('tel2', 'Codigo de area', 'trim|required|numeric');
                $this->form_validation->set_rules('tel3', 'Codigo de area', 'trim|required|numeric');
		$this->form_validation->set_rules('direccion', 'Direccion', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required');
                $this->form_validation->set_rules('imgsrc', 'Logo instituto', 'required|url');
		if ($this->form_validation->run() == FALSE)
		{
                      
                      $error = TRUE;
                        $this->load->view('home/header.php');
                        $this->load->model("city");
                        $city = new city;
                        $citys =  $city->getAllRecords();
                        $data["citys"] = $citys;
                        $this->load->view('home/cargar_instituto',$data);
                        $this->load->view('home/footer.php');
                    
		}
		else
		{
                   
                    $name = $this->input->post('nombre_institucion');
                    $address = $this->input->post('direccion');
                    $phone = $this->input->post('tel1') . $this->input->post('tel2') . $this->input->post('tel3');
                    $email = $this->input->post('email');
                    $facebook = $this->input->post('facebook');
                    $twitter = $this->input->post('twitter');
                    $photo = $this->input->post('imgsrc');
                    $ciudad = $this->input->post('ciudad');
                  
                    $slug_institucion  = gen_slug($name);   
                    $descripcion = $this->input->post('breve_descripcion');
                    
                        $sql_insert_institutes = "INSERT INTO institutes 
                                   (name, address, phone, email, facebook, twitter, photo, descripcion,city_id,slug) 
                            VALUES ('$name','$address','$phone','$email', '$facebook', '$twitter', '$photo', '$descripcion','$ciudad','$slug_institucion')";

                       $res_insert = $this->db->query($sql_insert_institutes);
                       
                      $row = $this->db->query("select MAX(id) as id FROM institutes")->result();
                      $instituto_id = $row[0]->id;
                        
                    
                        $DestinationDirectory           = '/home/expoeduc/public_html/beta/public/images/instituciones/';
                        rename($photoguarda,$DestinationDirectory . $instituto_id . ".jpg");
                        
                        $sql_users_institutes = "INSERT INTO usuarios_institutos
                                  (user_id, instituto_id) 
                           VALUES ('$user_id','$instituto_id')";
                     
                      
                 
                       $res_user_instituto = $this->db->query($sql_users_institutes);
                       
                       
                       
               }}
                
                
                IF($error == FALSE){                    //Ya está logueado - Publica el curso

                    $data = $this->session->userdata('curso');
              
          
                    $id_instituto = $this->verificar_usuario($user_id);
                    

                    //Datos Paso 1
                    $titulo = strtolower($data['titulo']);
                    $descripcion_corta = $data['descripcion_corta'];
                    $tipo_curso = $data['tipo_curso'];
                    $categoria = $data['categoria'];
                    $palabras_claves = str_replace(',', '-', $data['palabras_claves']);
                    $descripcion = $data['descripcion'];
                    $objetivos = $data['objetivos'];
                    $orientacion = $data['orientacion'];
                    $que_incluye = $data['que_incluye'];
                    $requisitos = $data['requisitos'];
                    $tipo_duracion = $data['tipo_duracion'];
                    $meses_duracion = $data['meses_duracion'];
                    $clases_semanales = $data['clases_semanales'];
                    $precio = $data['precio'];
                    $es_gratuita = $data['es_gratuita'];
                    $tipo_cobro = $data["tipo_cobro"];    
                    $valor_matricula = $data['valor_matricula'];
                    $matricula = $data['matricula'];
                    $modalidad = $data['modalidad'];
                    $fecha_inicio = $data['fecha_inicio_valor'];
                    $foto = $this->session->userdata('foto_curso');
                    $slug = gen_slug($titulo . "-" . $categoria);   

                    $sql_insert = "INSERT INTO cursos 
                                  (tipo_publicacion, titulo, descripcion_corta, categoria, palabras_claves,
                                  descripcion, objetivos, orientacion, que_incluye, requisitos, tipo_duracion, meses_duracion,
                                  clases_semanales, precio, es_gratuita, tiene_matricula,matricula, fecha_inicio,modalidad,foto, id_instituto, user_id,slug,tipo_cobro)
                                  VALUES
                                  (
                                   '$tipo_curso','$titulo','$descripcion_corta','$categoria','$palabras_claves',
                                   '$descripcion','$objetivos','$orientacion','$que_incluye','$requisitos','$tipo_duracion','$meses_duracion',
                                   '$clases_semanales','$precio','$es_gratuita','$matricula','$valor_matricula','$fecha_inicio','$modalidad','$foto','$id_instituto','$user_id','$slug',$tipo_cobro                          
                                   )";




                    $res = $this->db->query($sql_insert);

                    if ($res) {
                        
                        $this->session->userdata('curso');
                        $vista['curso_publicado'] = true;
                        $vista['titulo_curso'] = $titulo;

                        $this->load->view('home/header.php', $vista);
                        $this->load->view('home/index.php');
                        $this->load->view('home/footer.php');
                    } else {
                        $vista['curso_publicado'] = true;
                        $vista['error_publica_curso'] = true;
                        $this->load->view('home/header.php', $vista);
                        $this->load->view('home/index.php');
                        $this->load->view('home/footer.php');
                    }
                            }
        }
    function verificar() 
    {
        $this->load->model("user"); 
       $this->load->library('form_validation');
       $photoguarda = $this->input->post('imgsrc');
               
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
	$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
        $this->form_validation->set_rules('password_1', 'Contraseña', 'trim|required');
        
          if ($this->form_validation->run() == FALSE)
                {
                 $this->load->view('home/header.php');   
                 $this->load->view('registro/registro.php');
                 $this->load->view('home/footer.php');
                }else{
                    
                    
                   
        
                       $arrusuario = array(
                       
                       "email"=>$this->input->post('email'),
                       "password"=>  md5($this->input->post('password_2'))
                       
           
                       
                       );
           
           $user = $this->user->guardarUser($arrusuario);
         
            if($user == 1){;
        
          
            $this->auto_login($this->input->post('email'), $this->input->post('password_2'));
            redirect('registro/cargar_instituto');  
            }          
                    
                }
        
        
        
    
        }
    
    function verificar_publicar () 
    {
            $email = $this->input->post('email');
            $password_1 = $this->input->post('password_1');
            $password_2 = $this->input->post('password_2');
            //$nombre = $this->input->post('nombre');
            //$apellido = $this->input->post('apellido');
              $passnuevo = md5($password_1);
            $sql_insert = "INSERT INTO users (nombre,apellido,email, password) VALUES ('$nombre','$apellido','$email','$passnuevo')";
            $res = $this->db->query($sql_insert);
            if ($res) {
                //redirect('publica/registroOk');
                $data['mensaje_registro'] = 'Usuario registrado exitosamente';
                $this->load->view('home/header.php');
                $this->load->view('home/index.php', $data);
                $this->load->view('home/footer.php');
            }

            $this->publicar_curso();
    }
    function auto_login($email, $password) 
    {
        $this->load->model('user', '', true);

        $userData = $this->user->authenticate($email, $password);
        if ($userData) {
            $credentials = array('loggedin' => true, 'user_id' => $userData->id, 'data' => $userData);
            $this->session->set_userdata($credentials);
            $this->session->set_userdata($email);
         //   redirect('home', 'refresh');
        } else {
            redirect('sessions/user_login_fail');
        }
    }
    function resizeImage($CurWidth,$CurHeight,$MaxSize,$DestFolder,$SrcImage,$Quality,$ImageType)
    {
            //Check Image size is not 0
            if($CurWidth <= 0 || $CurHeight <= 0)
            {
                return false;
            }

            //Construct a proportional size of new image
            $ImageScale         = min($MaxSize/$CurWidth, $MaxSize/$CurHeight);
            $NewWidth           = ceil($ImageScale*$CurWidth);
            $NewHeight          = ceil($ImageScale*$CurHeight);

            if($CurWidth < $NewWidth || $CurHeight < $NewHeight)
            {
                $NewWidth = $CurWidth;
                $NewHeight = $CurHeight;
            }
            $NewCanves  = imagecreatetruecolor($NewWidth, $NewHeight);
            // Resize Image
    
            if(imagecopyresampled($NewCanves, $SrcImage,0, 0, 0, 0, $NewWidth, $NewHeight, $CurWidth, $CurHeight))
            {
                switch(strtolower($ImageType))
                {
                    case 'image/png':
                    
                        imagepng($NewCanves,$DestFolder);
                        break;
                    case 'image/gif':
                        imagegif($NewCanves,$DestFolder);
                        break;
                    case 'image/jpeg':
                    case 'image/pjpeg':
                        imagejpeg($NewCanves,$DestFolder,$Quality);
                        break;
                    default:
                        return false;
                }
            //Destroy image, frees up memory
            if(is_resource($NewCanves)) {imagedestroy($NewCanves);}
            return true;
            }

        }
    function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType)
    {
            //Check Image size is not 0
            if($CurWidth <= 0 || $CurHeight <= 0)
            {
                return false;
            }

            //abeautifulsite.net has excellent article about "Cropping an Image to Make Square"
            //http://www.abeautifulsite.net/blog/2009/08/cropping-an-image-to-make-square-thumbnails-in-php/
            if($CurWidth>$CurHeight)
            {
                $y_offset = 0;
                $x_offset = ($CurWidth - $CurHeight) / 2;
                $square_size    = $CurWidth - ($x_offset * 2);
            }else{
                $x_offset = 0;
                $y_offset = ($CurHeight - $CurWidth) / 2;
                $square_size = $CurHeight - ($y_offset * 2);
            }

            $NewCanves  = imagecreatetruecolor($iSize, $iSize);
            if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size))
            {
                switch(strtolower($ImageType))
                {
                    case 'image/png':
                        imagepng($NewCanves,$DestFolder);
                        break;
                    case 'image/gif':
                        imagegif($NewCanves,$DestFolder);
                        break;
                    case 'image/jpeg':
                    case 'image/pjpeg':
                        imagejpeg($NewCanves,$DestFolder,$Quality);
                        break;
                    default:
                        return false;
                }
            //Destroy image, frees up memory
            if(is_resource($NewCanves)) {imagedestroy($NewCanves);}
            return true;

            }

        }
        function loginUsuario(){
            
            
        $this->load->model('user', '', true);
        $email = $this->input->post('email');
        $password = $this->input->post('password');
        $redirect= $this->input->post('redirect');
        $resuesta ="";
        
         $this->load->library('form_validation');
         $this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
         $this->form_validation->set_rules('email', 'Usuario', 'trim|required');
         $this->form_validation->set_rules('password', 'Constraseña', 'trim|required');
           if ($this->form_validation->run() == FALSE)
                {
       
            $this->load->view('home/header.php');
            $this->load->view('registro/registro.php');
            $this->load->view('home/footer.php');    
            
           
               
               
                }else{
        
         
        $userData = $this->user->authenticate($email,$password);
        
     
        
        if($userData != false){
      
            $credentials = array('loggedin' => true, 'user_id' => $userData->id, 'data' => $userData);
            $this->session->set_userdata($credentials);
            $this->session->set_userdata($email);
            
            
            
       redirect($redirect);
            
            

        }else{
         
           
            $data["respuesta"] ="Error de usuario o contraseña vuelva a intentarlo.";
            $this->load->view('home/header.php');
            $this->load->view('registro/registro.php',$data);
            $this->load->view('home/footer.php');    
            
            
                }}
        
        
        
        
        
        
        
            
        }
        
        }

?>